package com.xiaoyu.cloud.config;



import com.xiaoyu.cloud.properties.RestTemplateProperties;
import org.apache.http.client.HttpClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.ResponseErrorHandler;
import org.springframework.web.client.RestTemplate;

import java.util.Collections;

@Configuration
public class RestTemplateConfig {
    @Autowired
    private RestTemplateProperties restTemplateProperties;
    @Autowired
    private HttpClient httpClient;


    @Bean
    @LoadBalanced
    public RestTemplate restTemplate(HttpComponentsClientHttpRequestFactory httpComponentsClientHttpRequestFactory) {
        RestTemplate restTemplate = new RestTemplate(httpComponentsClientHttpRequestFactory);
        restTemplate.setErrorHandler(new ResponseErrorHandler() {
            @Override
            public boolean hasError(ClientHttpResponse clientHttpResponse) {
                return false;
            }

            @Override
            public void handleError(ClientHttpResponse clientHttpResponse) {
                //默认处理非200的返回，会抛异常
            }
        });
        //restTemplate.setInterceptors(Collections.singletonList(new RestTemplateMdcInterceptor()));
        return restTemplate;
    }

    @Bean
    public RestTemplate restTemplateForIpPort(HttpComponentsClientHttpRequestFactory httpComponentsClientHttpRequestFactory) {
        return this.restTemplate(httpComponentsClientHttpRequestFactory);
    }

    @Bean
    public HttpComponentsClientHttpRequestFactory httpComponentsClientHttpRequestFactory() throws Exception {
        HttpComponentsClientHttpRequestFactory httpsFactory = new HttpComponentsClientHttpRequestFactory(httpClient);
        httpsFactory.setReadTimeout(restTemplateProperties.getReadTimeout());
        httpsFactory.setConnectTimeout(restTemplateProperties.getConnectTimeout());
        httpsFactory.setConnectionRequestTimeout(restTemplateProperties.getConnectionRequestTimeout());
        return httpsFactory;
    }


}
